package com.seeyon.apps.kkARPEvent.util;

import com.seeyon.apps.collaboration.api.CollaborationApi;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.ctp.cap.api.manager.CAPFormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.content.mainbody.MainbodyManager;
import com.seeyon.ctp.common.file.model.CtpLocalFile;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.util.Strings;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.List;

/**
 * Title : CAP4表单转PDF工具类
 * Author: chenxd
 * Date: 2023-12-4 10:36
 */
public class CAP4Form2PDFUtils {
    private static final Log logger = LogFactory.getLog(CAP4Form2PDFUtils.class);
    private static AffairManager affairManager = (AffairManager) AppContext.getBean("affairManager");
    private static CollaborationApi collaborationApi = (CollaborationApi) AppContext.getBean("collaborationApi");
    private static CAPFormManager capFormManager = (CAPFormManager) AppContext.getBean("capFormManager");
    private static MainbodyManager ctpMainbodyManager = (MainbodyManager) AppContext.getBean("ctpMainbodyManager");


    private static CAP4Form2PDFUtils instance;
    public static CAP4Form2PDFUtils getInstance(){
        if(instance == null){
            synchronized (CAP4Form2PDFUtils.class){
                if(instance == null){
                    instance = new CAP4Form2PDFUtils();
                }
            }
        }
        return instance;
    }

    public String writeForm2File(Long affairId) {
        String formHtml = "";
        try {
            CtpAffair affair = affairManager.get(affairId);
            ColSummary summary = collaborationApi.getColSummary(affair.getObjectId());

            // 临时文件根目录 .../base/temporary/pdfTemp/Id/
            String pdfTempFolder = PDFConstants.WRITE_TEMP_FOLDER + File.separator + Math.abs(affairId);

            File directory = new File(pdfTempFolder);
            if (!directory.exists()){
                if (directory.mkdirs()) {
                    logger.info("创建文件: " + directory.getAbsolutePath() + ",成功！");
                } else {
                    logger.info("创建文件: " + directory.getAbsolutePath() + ",失败！");
                }
            }

            StringBuffer formContent = new StringBuffer(
                    "<html> <head>  <meta charset=\"UTF-8\">  <title>表单</title> </head> <body style=\"text-align:center;\">");
            String affairUrl ="/collaboration/collaboration.do?method=showPrintForm&openFrom=listDone&affairId="+affairId+"&isShowComment=false&isReplyContent=false";
            String _rightId = collaborationApi.findRightIdbyAffairIdOrTemplateId(affair,summary.getTempleteId());
            if (Strings.isNotBlank(_rightId)&& "-1.-1".equals(_rightId)) {
                _rightId = "-1";
            }
            List<CtpContentAll> contentList = ctpMainbodyManager.getContentListByModuleIdAndModuleType(ModuleType.collaboration, summary.getId());
            CtpContentAll ctpContent = contentList.get(0);

            //这里获取的表单正文内容是转换后的图片
            String bodyContent = PDFCommonUtils.getInstance().getFormDataHtmlForRest(summary.getFormAppid(),ctpContent.getModuleId(),_rightId);
            formContent.append(bodyContent);
            //           String bodyContent = "base64图片";
//            formContent.append(bodyContent);
//获取意见
            formContent.append(PDFCommonUtils.getInstance().coverCommentHtml(ModuleType.collaboration,summary.getId(),800));

            formContent.append("</body></html>");
            formHtml += formContent.toString();

            String formName = affair.getSubject();
            String realFormName = PDFCommonUtils.getInstance().formatFileName(formName);

            String formHtmlFilePath = pdfTempFolder + File.separator + realFormName + ".html";
            File myFile = new File(formHtmlFilePath); // 指定文件名和路径
            if (myFile.createNewFile()) {
                logger.info("创建文件: " + myFile.getAbsolutePath() + ",成功！");
            } else {
                logger.info("创建文件: " + myFile.getAbsolutePath() + ",失败！");
            }

            CtpLocalFile formFile = new CtpLocalFile(myFile.getAbsolutePath());
            FileUtils.writeStringToFile(formFile, formHtml, "UTF-8");

            String pdfPath = pdfTempFolder + File.separator + realFormName + ".pdf";
            //将表单HTML 转成图片（因为表单HTML 中的展示URL，导入档案可能无法访问，所以，转成图片）
            if(Html2PDFExecute.transHtmlToPdf(pdfTempFolder + File.separator + realFormName + ".html", pdfPath)) {
                PDFCommonUtils.getInstance().putPath(String.valueOf(affair.getId()), pdfPath);
                logger.info("转PDF成功：path:" + pdfPath);
                return pdfPath;
            }
            logger.info("转PDF失败");
        }catch(Exception e) {
            logger.error("解析表单信息失败", e);
        }
        return "";
    }



}
